#pragma once

#include "log.hpp"
#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <unordered_map>

#define SIZE 1024

class UdpServer
{
public:
    UdpServer(uint16_t port, std::string ip = "") : _port(port), _ip(ip), _sock(-1)
    {
    }
    bool initServer()
    {
        // 创建套接字
        _sock = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sock < 0)
        {
            logMessage(FATAL, "%d:%s", errno, strerror(errno));
            exit(2);
        }
        // bind: 将ip和port在内核中和进程强关联
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        // INADDR_ANY 让服务器在工作过程中，可以从任意IP中获取数据
        local.sin_addr.s_addr = _ip.empty() ? INADDR_ANY : inet_addr(_ip.c_str());

        if (bind(_sock, (struct sockaddr *)&local, sizeof(struct sockaddr_in)) < 0)
        {
            logMessage(FATAL, "%d:%s", errno, strerror(errno));
            exit(2);
        }
        logMessage(NORMAL, "服务器初始化完成");
        return true;
    }

    void Start()
    {
        char buffer[SIZE];
        for (;;)
        {
            struct sockaddr_in peer; // 纯输出型参数
            bzero(&peer, sizeof(peer));
            socklen_t len = sizeof(peer); // 输入输出型参数 输入：peer缓冲区(结构体)大小, 输出:实际读到的peer
            // 读取数据
            ssize_t s = recvfrom(_sock, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
            char key[64];

            if (s > 0)
            {
                buffer[s] = 0;

                uint16_t cli_port = ntohs(peer.sin_port);
                std::string cli_ip = inet_ntoa(peer.sin_addr);
                // printf("[%s:%d]# %s\n", cli_ip.c_str(), cli_port, buffer);

                snprintf(key, sizeof(key), "%s-%d", cli_ip.c_str(), cli_port);
                logMessage(NORMAL, "key: %s", key);

                auto it = _users.find(key);
                if (it == _users.end())
                {
                    logMessage(NORMAL, "add new user: %s", key);
                    _users.insert({key, peer});
                }
            }

            // 写回数据
            for (auto &iter : _users)
            {
                std::string sendMessage = key;
                sendMessage += "#";
                sendMessage += buffer;
                logMessage(NORMAL, "push message to %s", iter.first.c_str());
                sendto(_sock, sendMessage.c_str(), sendMessage.size(), 0, (struct sockaddr *)&(iter.second), sizeof(iter.second));
            }
        }
    }
    ~UdpServer()
    {
        if (_sock >= 0)
            close(_sock);
    }

private:
    uint16_t _port;
    std::string _ip;
    int _sock;
    std::unordered_map<std::string, struct sockaddr_in> _users;
    // std::unordered_map<std::string, struct sockaddr_in> _users;
};